﻿using System;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class DimensionsRecord : BiffRecord
    {
        private ushort _colMac;
        private ushort _colMic;
        private uint _rwMac;
        private uint _rwMic;

        public DimensionsRecord(Worksheet worksheet)
        {
            if (worksheet.Cells.NonVolatileCells.Count > 0)
            {
                var range = (CellsRange) worksheet.UsedRange;
                _rwMic = (uint) range.Row;
                _rwMac = (uint) ((uint) range.Row + range.RowSpan);
                _colMic = (ushort) ((uint) range.Column );
                _colMac = (ushort) ((uint) range.Column + range.ColumnSpan);
            }
            if (worksheet.Tables.Count > 0)
            {
                if (worksheet.Cells.NonVolatileCells.Count == 0)
                {
                    _rwMic = uint.MaxValue;
                    _rwMac = uint.MinValue;
                    _colMic = ushort.MaxValue;
                    _colMac = ushort.MinValue;
 
                }
                _rwMic = Math.Min(_rwMic, (uint)Enumerable.Min(worksheet.Tables, t => t.Range.TopLeftCell.Row.Index));
                _rwMac = Math.Max(_rwMac, (uint)Enumerable.Max(worksheet.Tables, t => t.Range.Row + t.Range.RowSpan));
                _colMic = Math.Min(_colMic, (ushort)Enumerable.Min(worksheet.Tables, t => t.Range.Column));
                _colMac = Math.Max(_colMac, (ushort)Enumerable.Max(worksheet.Tables, t => t.Range.Column + t.Range.ColumnSpan));
            }
        }

        public DimensionsRecord()
        {
        }

        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.Dimensions; }
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            _rwMic = context.ReadUInt32();
            _rwMac = context.ReadUInt32();
            _colMic = context.ReadUInt16();
            _colMac = context.ReadUInt16();
            context.ReadUInt16();
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            context.WriteUInt32(_rwMic);
            context.WriteUInt32(_rwMac);
            context.WriteUInt16(_colMic);
            context.WriteUInt16(_colMac);
            context.WriteUInt16(0);
        }
    }
}